package com.fingard.dsp.bank.directbank.icbc02;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.directbank.icbc02.util.MybankPayInsurancePrimumChargeRequestV1;
import com.fingard.dsp.bank.directbank.icbc02.util.MybankPayInsurancePrimumChargeResponseV1;
import com.fingard.dsp.bank.directbank.icbc02.util.MybankPayInsurancePrimumChargeresultqryRequestV1;
import com.fingard.dsp.bank.directbank.icbc02.util.MybankPayInsurancePrimumChargeresultqryResponseV1;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.icbc.api.DefaultIcbcClient;

/**
 * 参考文档：中国工商银行代理保险保费代扣及协议管理API接口规范
 */
public class ICBC02RealTime extends ICBC02Base implements IRealTime {
    /**
     * 参考章节：中国工商银行代理保险客户保费单笔扣款
     * @param p_req9108
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
            if (actItem == null) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req9108.singleDetail.recAct + "]商户配置信息!";
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String aesKey = getBankConfig().getValueAsString("aesKey");
            String privateKey = FileHelper.readFileText(actItem.ownKeyStorePath, getCharset());
            String publicKey = FileHelper.readFileText(actItem.oppCertFilePath, getCharset());
            DefaultIcbcClient client = new DefaultIcbcClient(actItem.appId, "RSA2", privateKey, "UTF-8", "json", publicKey, "AES", aesKey, (String) null, (String) null);
            // 请求实体
            MybankPayInsurancePrimumChargeRequestV1 request = new MybankPayInsurancePrimumChargeRequestV1();
            // bizContent实体
            MybankPayInsurancePrimumChargeRequestV1.InsuranceCustPrtlChargeRequestV1Biz bizContent
                    = new MybankPayInsurancePrimumChargeRequestV1.InsuranceCustPrtlChargeRequestV1Biz();
            MybankPayInsurancePrimumChargeRequestV1.CommonReqInfo commonReqInfoContent
                    = new MybankPayInsurancePrimumChargeRequestV1.CommonReqInfo();
            MybankPayInsurancePrimumChargeRequestV1.TransReqInfo transReqInfoContent
                    = new MybankPayInsurancePrimumChargeRequestV1.TransReqInfo();
            MybankPayInsurancePrimumChargeRequestV1.BizContentInfo bizContentInfo =
                    new MybankPayInsurancePrimumChargeRequestV1.BizContentInfo();

            commonReqInfoContent.setChanNo("15");
            commonReqInfoContent.setInsuId(bankFront.corpNo);
            commonReqInfoContent.setTransDate(p_req9108.singleDetail.payDate);
            commonReqInfoContent.setTransTime(p_req9108.singleDetail.payTime);
            commonReqInfoContent.setZoneNo(actItem.areaCode);
            commonReqInfoContent.setBrNo(actItem.cnapsCode);

            transReqInfoContent.setCustName(p_req9108.singleDetail.payName);//客户姓名
            transReqInfoContent.setCustIdType(convertCertTypeToBank(p_req9108.singleDetail.certType));//客户证件类型CODE1
            transReqInfoContent.setCustIdNo(p_req9108.singleDetail.certNum);//客户证件号码
            transReqInfoContent.setPrtlNo(p_req9108.singleDetail.authCode);//协议编号
            transReqInfoContent.setInsuPrtlType("1");//保险公司协议种类CODE5
            transReqInfoContent.setInsuPrtlNo(p_req9108.singleDetail.insuPolicyNum);//投保单号/保单号
            transReqInfoContent.setTransSeq(p_req9108.singleDetail.askNumber);//交易流水号
            transReqInfoContent.setReptFlag("0");//重送标志CODE8
            transReqInfoContent.setTransAmt(StringHelper.amountMultiply100(p_req9108.singleDetail.payAmount));//交易金额(以分为单位)
            transReqInfoContent.setTransNotes(p_req9108.singleDetail.memo);//交易备注

            bizContentInfo.setCommonReqInfo(commonReqInfoContent);
            bizContentInfo.setTransReqInfo(transReqInfoContent);
            bizContent.setBizContentInfo(bizContentInfo);
            request.setServiceUrl(bankFront.getUrl("9108"));
            request.setBizContent(bizContent);

            WriteBankLogStep2(JSONObject.toJSONString(request));
            MybankPayInsurancePrimumChargeResponseV1 response = client.execute(request, p_req9108.reqHeader.transSeqID);
            WriteBankLogStep3(JSONObject.toJSONString(response));

            if ("0".equals(response.getRetCode())) {
                // 业务成功处理
                String respCode = response.getRetCode();
                String tmpRespInfo = response.getReturnMsg();
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpRespInfo;
                tmpRetDetail.transAmt = StringHelper.amountDivide100(response.getRespContent().getTransRepInfo().getTransAmt());
                tmpRetDetail.transState = respCode;
                tmpRetDetail.payInfoCode = respCode;
            } else {
                // 失败
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = response.getReturnMsg();
                tmpRetDetail.transState = PaymentState.FAIL;
                tmpRetDetail.payInfoCode = FailCode.E9981;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.toString();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    /**
     * 参考章节：中国工商银行代理保险客户保费单笔扣款结果查询
     * @param p_req9108
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9144.askNumber;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
            if (actItem == null) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req9144.recAct + "]商户配置信息!";
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String aesKey = getBankConfig().getValueAsString("aesKey");
            String privateKey = FileHelper.readFileText(actItem.ownKeyStorePath, getCharset());
            String publicKey = FileHelper.readFileText(actItem.oppCertFilePath, getCharset());
            DefaultIcbcClient client = new DefaultIcbcClient(actItem.appId, "RSA2", privateKey, "UTF-8", "json", publicKey, "AES", aesKey, (String) null, (String) null);
            // 请求实体
            MybankPayInsurancePrimumChargeresultqryRequestV1 request = new MybankPayInsurancePrimumChargeresultqryRequestV1();
            // bizContent实体
            MybankPayInsurancePrimumChargeresultqryRequestV1.InsuranceCustPrtlChargeresultqryRequestV1Biz bizContent
                    = new MybankPayInsurancePrimumChargeresultqryRequestV1.InsuranceCustPrtlChargeresultqryRequestV1Biz();
            MybankPayInsurancePrimumChargeresultqryRequestV1.CommonReqInfo commonReqInfoContent
                    = new MybankPayInsurancePrimumChargeresultqryRequestV1.CommonReqInfo();
            MybankPayInsurancePrimumChargeresultqryRequestV1.TransReqInfo transReqInfoContent
                    = new MybankPayInsurancePrimumChargeresultqryRequestV1.TransReqInfo();
            MybankPayInsurancePrimumChargeresultqryRequestV1.BizContentInfo bizContentInfo =
                    new MybankPayInsurancePrimumChargeresultqryRequestV1.BizContentInfo();

            commonReqInfoContent.setChanNo("15");
            commonReqInfoContent.setInsuId(bankFront.corpNo);
            commonReqInfoContent.setTransDate(Format.Date10Format.format(p_req9144.getBgnDateTime()));
            commonReqInfoContent.setTransTime(Format.Time8Format.format(p_req9144.getBgnDateTime()));
            commonReqInfoContent.setZoneNo(actItem.areaCode);
            commonReqInfoContent.setBrNo(actItem.cnapsCode);

            transReqInfoContent.setCustName(p_req9144.payName);//客户姓名
            transReqInfoContent.setCustIdType(convertCertTypeToBank(p_req9144.certType));//客户证件类型CODE1
            transReqInfoContent.setCustIdNo(p_req9144.certNum);//客户证件号码
            transReqInfoContent.setPrtlNo(p_req9144.authCode);//协议编号
            transReqInfoContent.setTransSeq(p_req9144.askNumber);//交易流水号

            bizContentInfo.setCommonReqInfo(commonReqInfoContent);
            bizContentInfo.setTransReqInfo(transReqInfoContent);
            bizContent.setBizContentInfo(bizContentInfo);
            request.setServiceUrl(bankFront.getUrl("9144"));
            request.setBizContent(bizContent);

            WriteBankLogStep2(JSONObject.toJSONString(request));
            MybankPayInsurancePrimumChargeresultqryResponseV1 response = client.execute(request, p_req9144.reqHeader.transSeqID);
            WriteBankLogStep3(JSONObject.toJSONString(response));

            if ("0".equals(response.getRetCode())) {
                // 业务成功处理
                String respCode = response.getRetCode();
                String tmpRespInfo = response.getReturnMsg();
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpRespInfo;
                tmpRetDetail.transAmt = StringHelper.amountDivide100(response.getRespContent().getTransRepInfo().getTransAmt());
                String status = response.getRespContent().getTransRepInfo().getTransStatus();
                if ("0".equals(status)) {
                    tmpRetDetail.transState = PaymentState.SUCCESS;
                } else if ("1".equals(status)) {
                    tmpRetDetail.transState = PaymentState.FAIL;
                } else if ("2".equals(status)) {
                    tmpRetDetail.transState = PaymentState.PAYING;
                }
                tmpRetDetail.payInfoCode = respCode;
            } else {
                // 失败
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = response.getReturnMsg();
                tmpRetDetail.transState = PaymentState.FAIL;
                tmpRetDetail.payInfoCode = FailCode.E9981;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.toString();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }
}
